# -*- encoding=utf-8 -*-

import pymysql, os, configparser
from pymysql.cursors import DictCursor
from DBUtils.PooledDB import PooledDB

__all__ = ['FlowRecord']
__author__ = 'yongyong.mu'


class MyPymysqlPool(object):
    """
        数据库连接池
    """
    __pool = None

    def __init__(self):
        self._conn = self.__getConn()
        self._cursor = self._conn.cursor()

    @staticmethod
    def __getConn():
        if MyPymysqlPool.__pool is None:
            # __pool = PooledDB(creator=pymysql, maxcached=5, host='127.0.0.1', port=3306, user='root',
            #                   passwd='mysql', db='safepf', charset="utf8", cursorclass=DictCursor)

            __pool = PooledDB(creator=pymysql, maxcached=5, host='127.0.0.1', port=3306, user='insec',
                              passwd='InSec888!', db='safeplatform', charset="utf8", cursorclass=DictCursor)
        return __pool.connection()

    def getAll(self, sql):
        count = self._cursor.execute(sql)
        # if count > 0:
        result = self._cursor.fetchall()
        # else:
        #     result = ''
        return result

    def getOne(self, sql):
        count = self._cursor.execute(sql)
        result = self._cursor.fetchone()
        return result

    def writeOne(self, sql):
        self._cursor.execute(sql)
        self._conn.commit()
        return True

    def writeMany(self, sql):
        self._cursor.executemany(sql)
        self._conn.commit()

    def dispose(self, isEnd=1):
        self._cursor.close()
        self._conn.close()


if __name__ == "__main__":
    mysql = MyPymysqlPool()
    # sql = "select rt_bps, avg_bps from t_mem_net_flow order by interface_id"
    # result = mysql.getAll(sql)
    # for res in result:
    #     print(res['rt_bps'])
    # mysql.dispose()
